﻿/*
 * 由SharpDevelop创建。
 * 用户： Administrator
 * 日期: 2018/7/20
 * 时间: 19:44
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Drawing;
using System.Windows.Forms;

namespace MiniTextViewer
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		string[] lines;
		FilePosition position;
		
		const int ShowCharCount = 18;
		
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			lines = null;
			position = null;
		}
		
		void MainFormDragDrop(object sender, DragEventArgs e)
		{
			var s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
			
			if (s.Length > 0)
			{
				LoadFile(s[0]);
			}
		}
		
		void MainFormDragEnter(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(DataFormats.FileDrop))
			{
				e.Effect = DragDropEffects.All;
			}
			else
			{
				e.Effect = DragDropEffects.None;
			}
		}
		
		void LoadFile(string filename)
		{
			lines = FileManager.GetInstance("main").GetFileLines(filename);
			position = FileManager.GetInstance("main").GetFilePosition(filename);
			
			Location = new Point(480, 0);
			Size = new Size(320, 52);
			FormBorderStyle = FormBorderStyle.None;
			Opacity = 0.2;
//			BackColor = Color.Transparent;
			ShowInTaskbar = false;
			lbTips.TextAlign = ContentAlignment.TopLeft;
			lbTips.Font = new Font("宋体", 12);
			lbTips.ForeColor = SystemColors.WindowText;
			
			UpdateUI();
		}
		
		void UpdateUI()
		{
			string content = lines[position.LineNum];
			if (position.LinePosition < 0)
			{
				position.LineNum--;
				content = lines[position.LineNum];
				int p = content.Length / ShowCharCount;
				int v = content.Length % ShowCharCount;
				position.LinePosition = p * ShowCharCount;
				if (v == 0)
					position.LinePosition -= ShowCharCount;
				UpdateUI();
				return;
			}
			int showCount = ShowCharCount;
			if (content.Length - position.LinePosition < ShowCharCount)
				showCount = content.Length - position.LinePosition;
			if (showCount < 0)
				showCount = 0;
			if (showCount == 0)
			{
				position.LineNum++;
				position.LinePosition = 0;
				UpdateUI();
				return;
			}
			
			string text = content.Substring(position.LinePosition, showCount);
			lbTips.Text = text;
		}
		
		void MainFormKeyDown(object sender, KeyEventArgs e)
		{
			Keys key = e.KeyCode;
			
			if (key == Keys.A || key == Keys.W)	// 向前翻页
				position.LinePosition -= ShowCharCount;
			else if (key == Keys.D || key == Keys.S)	// 向后翻页
				position.LinePosition += ShowCharCount;
			else if (key == Keys.Q)	// 隐藏主界面
				this.Hide();
			
			FileManager.GetInstance("main").UpdateFilePosition(position);
			
			UpdateUI();
		}
	}
}
